package cn.iocoder.yudao.module.system.controller.admin.normalquestioncontent;

import cn.iocoder.yudao.module.system.controller.admin.normalquestioncontent.vo.NormalQuestionContentPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.normalquestioncontent.vo.NormalQuestionContentRespVO;
import cn.iocoder.yudao.module.system.controller.admin.normalquestioncontent.vo.NormalQuestionContentSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.normalquestioncontent.NormalQuestionContentDO;
import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import cn.iocoder.yudao.module.system.dal.mysql.oauth2.OAuth2AccessTokenMapper;
import cn.iocoder.yudao.module.system.service.normalquestioncontent.NormalQuestionContentService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserId;


@Tag(name = "管理后台 - AI 报告")
@RestController
@RequestMapping("/system/ai/normal-question-content")
@Validated
public class NormalQuestionContentController {

    @Resource
    private OAuth2AccessTokenMapper oAuth2AccessTokenMapper;
    @Resource
    private NormalQuestionContentService normalQuestionContentService;

    @PostMapping("/create")
    @Operation(summary = "创建AI 报告")
    @PreAuthorize("@ss.hasPermission('ai:normal-question-content:create')")
    public CommonResult<Long> createNormalQuestionContent(@Valid @RequestBody NormalQuestionContentSaveReqVO createReqVO) {
        return success(normalQuestionContentService.createNormalQuestionContent(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新AI 报告")
    @PreAuthorize("@ss.hasPermission('ai:normal-question-content:update')")
    public CommonResult<Boolean> updateNormalQuestionContent(@Valid @RequestBody NormalQuestionContentSaveReqVO updateReqVO) {
        normalQuestionContentService.updateNormalQuestionContent(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除AI 报告")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('ai:normal-question-content:delete')")
    public CommonResult<Boolean> deleteNormalQuestionContent(@RequestParam("id") Long id) {
        normalQuestionContentService.deleteNormalQuestionContent(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得AI 报告")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('ai:normal-question-content:query')")
    public CommonResult<NormalQuestionContentRespVO> getNormalQuestionContent(@RequestParam("id") Long id) {
        NormalQuestionContentDO normalQuestionContent = normalQuestionContentService.getNormalQuestionContent(id);
        return success(BeanUtils.toBean(normalQuestionContent, NormalQuestionContentRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得AI 报告分页")
    @PermitAll
    public CommonResult<PageResult<NormalQuestionContentRespVO>> getNormalQuestionContentPage(@Valid NormalQuestionContentPageReqVO pageReqVO, HttpServletRequest request) {
//        String token = request.getHeader("authorization");
//        String[] tokenArr = token.split(" ");
//        OAuth2AccessTokenDO oAuth2AccessTokenDO = oAuth2AccessTokenMapper.selectByAccessToken(tokenArr[1]);
//        System.out.println("解析后: " + oAuth2AccessTokenDO);
        Long userId = getLoginUserId();

        if (userId != null) {
            pageReqVO.setUserId(userId.intValue());
        }
        PageResult<NormalQuestionContentDO> pageResult = normalQuestionContentService.getNormalQuestionContentPage(pageReqVO);

        return success(BeanUtils.toBean(pageResult, NormalQuestionContentRespVO.class));
    }


    @GetMapping("/categoryList")
    @Operation(summary = "获得AI 报告列表")
    @PermitAll
    public CommonResult<List<NormalQuestionContentRespVO>> getNormalQuestionContentList(@Valid NormalQuestionContentRespVO pageReqVO) {
        List<NormalQuestionContentDO> list = normalQuestionContentService.getCategoryList(pageReqVO.getParentType());
        return success(BeanUtils.toBean(list, NormalQuestionContentRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出AI 报告 Excel")
    @PreAuthorize("@ss.hasPermission('ai:normal-question-content:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportNormalQuestionContentExcel(@Valid NormalQuestionContentPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<NormalQuestionContentDO> list = normalQuestionContentService.getNormalQuestionContentPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "AI 报告.xls", "数据", NormalQuestionContentRespVO.class,
                        BeanUtils.toBean(list, NormalQuestionContentRespVO.class));
    }

    @PostMapping("/generate-major-contents")
    @Operation(summary = "生成专业内容")
    @PreAuthorize("@ss.hasPermission('ai:normal-question-content:create')")
    public CommonResult<Integer> generateMajorContents() {
        int count = normalQuestionContentService.generateMajorContents();
        return success(count);
    }

    @PostMapping("/generate-major-contents-public")
    @Operation(summary = "生成专业内容（公开接口）")
    @PermitAll
    public CommonResult<Integer> generateMajorContentsPublic() {
        int count = normalQuestionContentService.generateMajorContents();
        return success(count);
    }

}